import math


# 定义球面距离计算函数（Haversine formula）
def haversine(lon1, lat1, lon2, lat2):
    # 将经纬度转换为弧度
    lon1, lat1, lon2, lat2 = map(math.radians, [lon1, lat1, lon2, lat2])

    # 计算差值
    dlon = lon2 - lon1
    dlat = lat2 - lat1

    # 使用 Haversine formula 计算距离
    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))
    distance = 6371000 * c  # 地球半径为6371公里，乘以1000转换为米
    return distance


# 计算多边形中心点的经纬度坐标
def calculate_polygon_center(polygon):
    num_points = len(polygon)
    sum_lon = sum(p[0] for p in polygon)
    sum_lat = sum(p[1] for p in polygon)
    center_lon = sum_lon / num_points
    center_lat = sum_lat / num_points
    return center_lon, center_lat


def point_in_polygon(point, polygon):
    """
    判断点是否位于多边形内部

    Args:
        point: 待判断的点，(longitude, latitude)
        polygon: 多边形的顶点坐标列表，[(longitude1, latitude1), (longitude2, latitude2), ...]

    Returns:
        bool: 如果点位于多边形内部，返回 True；否则返回 False
    """
    lon, lat = point
    num_vertices = len(polygon)
    inside = False
    for i in range(num_vertices):
        j = (i + 1) % num_vertices
        if (polygon[i][0] > lon) != (polygon[j][0] > lon) and \
                (lat < (polygon[j][1] - polygon[i][1]) * (lon - polygon[i][0]) / (polygon[j][0] - polygon[i][0]) +
                 polygon[i][1]):
            inside = not inside
    return inside

# # 定义四个经纬度点组成的多边形区域
# polygon = [(108.900139, 34.374853), (108.900188, 34.374782), (108.900276, 34.374819), (108.900252, 34.374886)]
# point = (108.90045168921881, 34.37488246985623)
# # 计算多边形中心点的经纬度坐标
# center_lon, center_lat = calculate_polygon_center(polygon)
#
# # 计算待判断点到多边形中心点的距离
# distance = haversine(point[0], point[1], center_lon, center_lat)
#
# print("距离:", distance, "米")
